# -*- coding: utf-8 -*-

'''eof
name:申请企业未结清借贷余额到期期限占比分布
code:EC67_EntUnsettledTimLimitDistribution
tableName:
columnName:
groups:企业征信
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import pandas as pd
import json

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

# 获取表信息方法
def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]

# 时间信息格式化方法
def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date


# 数值判断方法
def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def EC67_EntUnsettledTimLimitDistribution():
    try:
        data = EC_DSJ_2D['data']
        flag = []
        # 信用提示信息
        EBA = getTable(data, 'EBA', 1, 1)
        if EBA == [{}]:
            TotalBalance =  u'缺失值'
        elif EBA == 0:
            TotalBalance = 0
        else:
            EB01 = getTable(EBA[0], 'EB01', 1, 0)
            if EB01 == 0:
                TotalBalance = 0
            elif EB01 == [{}]:
                TotalBalance = u'缺失值'
            else:
                #  信贷交易提示信息段
                EB01A = getTable(EB01[0], 'EB01A', 0, 1)
                if EB01A == 0:
                    TotalBalance = 0
                else:
                    # 借贷交易余额
                    EB01AJ01 = EB01A[0].get('EB01AJ01')
                    if isfloat(EB01AJ01) is False:
                        TotalBalance = u'缺失值'
                    else:
                        TotalBalance = float(EB01AJ01)
        # 明细汇总
        dict_bal = {'6个月':[0], '1年':[0], '1-3年':[0], '3年以上':[0]}
        # 信用提示信息
        EDA = getTable(data, 'EDA', 1, 0)
        if EDA == [{}]:
            flag.append(None)
        elif EDA == 0:
            flag.append(0)
        else:
            ED01 = getTable(EDA[0], 'ED01', 0, 1)
            if ED01 == 0:
                flag.append(0)
            elif ED01 == [{}]:
                flag.append(None)
            else:
                for i in ED01:
                    try:
                        #  基本信息段
                        ED01A = getTable(i, 'ED01A', 1, 1)
                        # 还款表现信息段
                        ED01B = getTable(i, 'ED01B', 1, 1)
                        if ED01A == 0 or ED01B == 0:
                            flag.append(0)
                        elif ED01A == [{}] or ED01B == [{}]:
                            flag.append(None)
                        else:
                            # 账户活动状态
                            ED01AD01 = ED01A[0].get('ED01AD01')
                            # 到期日期
                            ED01AR02 = ED01A[0].get('ED01AR02')
                            # 报告日期
                            ED01AR04 = ED01A[0].get('ED01AR04')
                            # 还款表现信息
                            ED01BH = getTable(ED01B[0], 'ED01BH', 0, 1)
                            if ED01BH == 0:
                                flag.append(0)
                            elif ED01BH == [{}]:
                                flag.append(None)
                            else:
                                flag1 = []
                                yue_dict = {}
                                for j in ED01BH:
                                    # 日期
                                    ED01BR02 = j.get('ED01BR02')
                                    # 余额
                                    ED01BJ01 = j.get('ED01BJ01')
                                    if dateFormat(ED01BR02) is None or isfloat(ED01BJ01) is False:
                                        flag1.append(None)
                                    else:
                                        flag1.append(0)
                                        yue_dict.update({dateFormat(ED01BR02).strftime('%Y%m%d'): float(ED01BJ01)})
                                if 0 in flag1:
                                    yue = yue_dict[max(yue_dict.keys())]
                                else:
                                    yue = None
                                if ED01AD01 in null_type_list or dateFormat(ED01AR02) is None or yue is None or dateFormat(ED01AR04) is None:
                                    flag.append(None)
                                else:
                                    flag.append(0)
                                    aaa = [(dateFormat(ED01AR02) + pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') for i in [-36, -12, -6, 0]]
                                    if str(ED01AD01) == '1':
                                        if aaa[2] <= dateFormat(ED01AR04).strftime('%Y%m%d') and  dateFormat(ED01AR04).strftime('%Y%m%d') < aaa[3]:
                                            dict_bal['6个月'].append(yue)
                                        elif  dateFormat(ED01AR04).strftime('%Y%m%d') < aaa[2] and aaa[1] <= dateFormat(ED01AR04).strftime('%Y%m%d'):
                                            dict_bal['1年'].append(yue)
                                        elif  dateFormat(ED01AR04).strftime('%Y%m%d') < aaa[1] and aaa[0] <= dateFormat(ED01AR04).strftime('%Y%m%d'):
                                            dict_bal['1-3年'].append(yue)
                                        elif aaa[0] > dateFormat(ED01AR04).strftime('%Y%m%d'):
                                            dict_bal['3年以上'].append(yue)
                    except:
                        flag.append(None)
                        continue
        factorNotNone = list(filter(lambda x: x is not None, flag))
        if len(factorNotNone) == 0:
            return json.dumps({'Dict_bal': u"缺失值", 'Dict_bal_ratio': u"缺失值"}, ensure_ascii=False)
        else:
            for key_i in dict_bal.keys():
                dict_bal.update({key_i: sum(dict_bal[key_i])})

            if TotalBalance == u"缺失值":
                dict_bal_ratio = u"缺失值"
            else:
                dict_bal_ratio = dict_bal.copy()
                if TotalBalance == 0:
                    for k in dict_bal_ratio.keys():
                        dict_bal_ratio.update({k: 0}) if dict_bal_ratio[k] == 0 else dict_bal_ratio.update({k: u"缺失值"})
                else:
                    for k in dict_bal_ratio.keys():
                        dict_bal_ratio.update({k: round(dict_bal[k]/TotalBalance, 4)})
            return json.dumps({'Dict_bal': dict_bal, 'Dict_bal_ratio': dict_bal_ratio}, ensure_ascii=False)
    except:
        return json.dumps({'Dict_bal': u"缺失值", 'Dict_bal_ratio': u"缺失值"}, ensure_ascii=False)


result = EC67_EntUnsettledTimLimitDistribution()

